<template>
  <div>
    <h4 class="title">评论发布区域</h4>
    <textarea class="textcontent" rows="7" placeholder="说点儿什么吧" maxlength="140" v-model="newmsg"></textarea>
    <mt-button type='primary' size='large' @click="newconment()">发布</mt-button>
    <div v-for="val in userconment" :key="val.userName">
      <span class="username">用户名：{{val.userName}}</span>
      <span class="time">{{val.time}}</span>
      <p class="userconment">{{val.msg}}</p>
    </div>
  </div>
</template>

<script>
import { Toast } from 'mint-ui'
export default {
  data () {
    return {
      userconment: [],
      newmsg: ''
    }
  },
  created () {
    this.getconments()
  },
  methods: {
    getconments () {
      this.axios.get('conments.json').then(
        rs => {
          this.userconment = rs.data
          for (var i = 0; i < this.userconment.length; i++) {
            this.userconment[i].time = '时间：' + this.userconment[i].time + '分钟前'
          }
          console.log(rs.data)
        },
        err => {
          Toast('数据获取失败')
          console.log(err)
        }
      )
      console.log('')
    },
    // 提交新评论
    newconment () {
      this.newmsg.trim()
      // 判断评论文本框中内容是否为空
      if (this.newmsg === '') {
        Toast({
          message: '评论内容不能为空',
          duration: 2000,
          position: 'top'
        })
      } else {
        // 创建一个对象用于存储新评论的进本信息
        var newmsgs = {}
        newmsgs.userName = '游客666'
        newmsgs.time = '时间：0分钟前'
        newmsgs.msg = this.newmsg
        // 将新评论对象添加到 useconment数组中的第一个位置 使用UNshift()方法
        this.userconment.unshift(newmsgs)
        console.log(this.newmsg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.username,.time{
  margin-top: 10px;
  font-size: 13px;
  font-weight: 100;
  display: inline-block;
  width: 50%;
  background-color: rgba(20,50,140,0.2);
}
</style>
